package space.hyf.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.Util;
import org.springframework.stereotype.Component;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * @Description: ip记录
 * @Author: HCode
 * @Date: 2022-08-18
 */
@Slf4j
@Component
public class IpAddressUtils {
    /**
     * 在Nginx等代理之后获取用户真实IP地址
     *
     * @param request
     * @return
     */
    private static final String KEY = "7N5BZ-7OOK6-72BSK-EWHKI-OTUI6-C6BLO";

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    log.error("getIpAddress exception:", e);
                }
                ip = inet.getHostAddress();
            }
        }
        return StringUtils.substringBefore(ip, ",");
    }


    public static String getCityInfo(String ip) {
        if (ip == null || !Util.isIpAddress(ip)) {
            log.error("Error: Invalid ip address");
            return "";
        }
        String ipInfo = "";
        try {
            // 获取地址经纬度
            String response = sendGet(ip);
            if ("".equals(response)) {
                System.out.println("IP地址无法解析");
            } else if ("内网IP".equals(response)) {
                ipInfo = "内网IP" + "-" + "内网IP";
            } else {
                JSONObject obj = JSONObject.parseObject(response);
                JSONObject addressInfo = (JSONObject) obj.get("location");
                // 获取经纬度
                String longitude = String.valueOf(addressInfo.get("lng"));
                String latitude = String.valueOf(addressInfo.get("lat"));
                String detail = sendLongitude_Latitude(longitude, latitude);
                if ("".equals(detail)) {
                    ipInfo = addressInfo.get("nation") + (String) addressInfo.get("province");
                } else {
                    JSONObject detail_obj = JSONObject.parseObject(detail);
                    String nation = (String) detail_obj.get("nation");
                    String province = (String) detail_obj.get("province");
                    String city = (String) detail_obj.get("city");
                    String district = (String) detail_obj.get("district");
                    String street_number = (String) detail_obj.get("street_number");
                    ipInfo = nation + "-" + province + "-" + city + "-" + district + "-" + street_number;
                }
            }
        } catch (Exception e) {
            log.error("getCityInfo exception:", e);
        }
        return ipInfo;
    }

    //根据在腾讯位置服务上申请的key进行请求操作
    public static String sendGet(String ip) {
        try {
            String url = "https://apis.map.qq.com/ws/location/v1/ip";
            String response = HttpUtils.sendGet(url, "ip=" + ip + "&key=" + KEY, "UTF-8");
            JSONObject obj = JSONObject.parseObject(response);
            String message = (String) obj.get("message");
            if ("Success".equals(message)) {
                JSONObject result = (JSONObject) obj.get("result");
                return result.toString();
            } else if ("局域网IP".equals(message)) {
                return "内网IP";
            }else {
                return "内网IP";
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
        }
        return "";
    }

    public static String sendLongitude_Latitude(String longitude, String latitude) {
        /*
        根据经纬度获取精确位置
         */
        String url = "https://apis.map.qq.com/ws/geocoder/v1/";
        String response = HttpUtils.sendGet(url, "location=" + latitude + "," + longitude + "&key=" + KEY, "UTF-8");
        JSONObject obj = JSONObject.parseObject(response);
        String message = (String) obj.get("message");
        if ("query ok".equals(message)) {
            JSONObject result = (JSONObject) obj.get("result");
            JSONObject address_component = result.getJSONObject("address_component");
            return address_component.toString();
        } else {
            return "";
        }
    }

    public static void main(String[] args) {
        String test = "中国-江西省-南昌市-进贤县-李渡镇";
        System.out.println(Arrays.toString(test.split("\\-")));
    }
}